﻿using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;

namespace _RobotInspection.Services
{
    public class WebSocketService
    {
        private readonly ILogger<WebSocketService> _logger;
        private readonly ConcurrentDictionary<string, WebSocket> _clients = new();
        
        // 添加消息处理事件
        public event Func<string, Task> MessageReceived;

        public WebSocketService(ILogger<WebSocketService> logger)
        {
            _logger = logger;
        }

        public async Task HandleConnection(WebSocket webSocket)
        {
            var clientId = Guid.NewGuid().ToString();
            _clients.TryAdd(clientId, webSocket);

            try
            {
                var buffer = new byte[1024 * 4];
                var receiveBuffer = new List<byte>();

                while (webSocket.State == WebSocketState.Open)
                {
                    var result = await webSocket.ReceiveAsync(
                        new ArraySegment<byte>(buffer),
                        CancellationToken.None
                    );

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        break;
                    }

                    // 处理文本消息
                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        receiveBuffer.AddRange(new ArraySegment<byte>(buffer, 0, result.Count));

                        if (result.EndOfMessage)
                        {
                            var message = Encoding.UTF8.GetString(receiveBuffer.ToArray());
                          //  Console.WriteLine(message);
                            receiveBuffer.Clear();

                            // 触发消息接收事件
                            if (MessageReceived != null)
                            {
                                try
                                {
                                    await MessageReceived.Invoke(message);
                                  
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError(ex, "处理接收消息时发生错误");
                                }
                            }
                        }
                    }
                }
            }
            catch (WebSocketException wsEx)
            {
                _logger.LogError(wsEx, "WebSocket连接异常");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "WebSocket连接出错");
            }
            finally
            {
                _clients.TryRemove(clientId, out _);
                if (webSocket.State == WebSocketState.Open)
                {
                    await webSocket.CloseAsync(
                        WebSocketCloseStatus.NormalClosure,
                        "连接关闭",
                        CancellationToken.None
                    );
                }
            }
        }


        // 在其他地方使用时
        //_webSocketService.MessageReceived += async(message) =>
        //    {
        //        // 处理接收到的消息
        //       Console.WriteLine(message);
        //    };
    public async Task BroadcastMessage(string message)
        {
            var messageBytes = Encoding.UTF8.GetBytes(message);
            var deadSockets = new List<string>();

            foreach (var client in _clients)
            {
                try
                {
                    if (client.Value.State == WebSocketState.Open)
                    {
                        await client.Value.SendAsync(
                            new ArraySegment<byte>(messageBytes),
                            WebSocketMessageType.Text,
                            true,
                            CancellationToken.None
                        );
                    }
                    else
                    {
                        deadSockets.Add(client.Key);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "发送WebSocket消息失败");
                    deadSockets.Add(client.Key);
                }
            }

            foreach (var socketId in deadSockets)
            {
                _clients.TryRemove(socketId, out _);
            }
        }
    }
}
